/* eslint-disable */
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
// import Vue from 'vue'
require('es6-promise').polyfill();
import App from './App'
import router from './router'
import VueLazyload from 'vue-lazyload'

import { sync } from 'vuex-router-sync'
import './config.js'
// import Vuex from 'vuex'
// Vue.use(Vuex)
import { ToastPlugin } from 'ckjrweb-mp-ui/src/components/index'
import loading from '@/plugin/loading/index'
import cjConfirm from '@/plugin/cjConfirm/index'
import previewImg from '@/plugin/previewImg/index'
import picturePreview from '@/plugin/picturePreview/index'
import Popup from '@/plugin/popup';
import ActionSheet from '@/plugin/actionSheet';
import CjClocker from '@/plugin/cjClocker';
Vue.use(Popup);
Vue.use(ActionSheet);
Vue.use(CjClocker);
Vue.use(loading)
Vue.use(cjConfirm)
Vue.use(picturePreview)
Vue.use(previewImg)
Vue.use(ToastPlugin)
import { isMplivePage } from '@/utils/goCsdptPage.js'
import { unLookPath } from '@/utils/visitorUnLookPath.js'
import { initReport } from '@/utils/dataReport.js'
import { ckjrRequest } from '@/utils/http.js'
// import { reportLog } from '@/utils/aegisReport.js'
import { utilJs } from '@/utils/common.js'
import '@/icons'
initReport();
// Vue.prototype.$reportLog = reportLog;

import store from './store/index.js'
import { getLoginSource } from '@/utils/globalUtil.js'
import { checkApiHp } from '@/utils/apihpCheck';

sync(store, router);


Vue.config.productionTip = false

//vue全局错误监听捕获 creatBy 小柯
const ENV = process.env.VUE_APP_ENV;
if (ENV != 'dev') {
  Vue.config.errorHandler = function (err, vm, info) {
    // handle error
    // `info` 是 Vue 特定的错误信息，比如错误所在的生命周期钩子
    // 只在 2.2.0+ 可用
    //   {
    //     message, // 异常信息
    //     name, // 异常名称
    //     script, // 异常脚本url
    //     line, // 异常行号
    //     column, // 异常列号
    //     stack  // 异常堆栈信息
    // }
    let errorData = {
      sourceUrl: '',
      sourceData: '',
      errorRes: JSON.stringify(err.stack),
      token: localStorage.getItem("token"),
      userId: localStorage.getItem("userId"),
      companyId: localStorage.getItem("companyId"),
      curPageUrl: window.location.href,
      uA: navigator.userAgent,
    }
    utilJs.reprotError(errorData);
  }
}

var curl = window.location.href;
var reg = /^\?(\&*\w+=*\w*\&*)*#$/;
if (curl.split("/")[5] != '?#') {
  if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && curl.split("/")[5] == '#') {
    var newHref = curl.split("#")[0] + '?#' + curl.split("#")[1];
    window.location.replace(newHref);
  } else if (curl.split("/")[5] == "?") {
    if (curl.split("?").length == 2) {
      var newHref = curl.split("?")[0] + '?#' + curl.split("?")[1];
    } else if (curl.split("?").length > 2) {
      var newHref = curl.split("?")[0] + '?#' + curl.split("?")[1] + '?' + curl.split("?")[2];
    }
    window.location.replace(newHref);
  } else if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) && reg.test(curl.split("/")[5])) {
    var newHref = curl.split("?")[0] + '?#' + curl.split("#")[1];
    window.location.replace(newHref);
  }
}
//进入系统的时候，缓存分享人id到sessionStorage,
const curQuery = utilJs.parseUrlQueryParams(curl);
if(curQuery.refereeId){
  sessionStorage.setItem('shareFromUserId', curQuery.refereeId);
}
//获取公司id以及设置门店id
const cId = utilJs.getCompanyIdByHerf();
utilJs.setStoreId();

router.beforeEach(function (to, from, next) {
  //如果是csdpt页面，那么直接跳转到csdpt页面吧
  if (curl.split('/')[3] == 'kpv2p' && isMplivePage(to.path)) {
    let liveUrl = `${window.location.origin}/kpv2plive/${curl.split("/")[4]}/?#${to.fullPath}`;
    window.location.replace(liveUrl);
    return;
  }
  // 缓存小程序是否开启客服系统
  if (to.query && to.query.isCustServiceOpen) {
    window.localStorage.setItem("isCustServiceOpen", to.query.isCustServiceOpen);
  }
  // 缓存小程序是否是0406版本，需要做旧版兼容
  if (to.query && to.query.version) {
    window.localStorage.setItem("wxAppVersion", to.query.version);
  }
  // 缓存小程序是否企业微信内打开，pc端企微打开小程序，无法根据userAgent判断是否是企微环境，没有关键字wxwork
  // 所以需要靠小程序那边获取environment后传参过来
  if (to.query && to.query.environment) {
    window.localStorage.setItem("wxAppEnvironment", to.query.environment);
  }
  // 缓存小程序是否履约小程序
  if (to.query && to.query.isKpStudy) {
    if (!localStorage.getItem(('isWxApp'))) {
      utilJs.checkWxApp();
    }
    window.sessionStorage.setItem("isKpStudy", 1);
  }
  // 如果是直播iframe套壳打开mp项目--start
  let liveGlobalData = store.state.live.globalData || {};
  if(to.query && to.query.goodsRoomId){
    liveGlobalData.goodsRoomId = to.query.goodsRoomId;
  }
  if(to.query && to.query.openFromBy){
    liveGlobalData.openFromBy = to.query.openFromBy;
    if(to.query.openModuleBy) {
      liveGlobalData.openByModule =  to.query.openModuleBy;
    }
  }
  store.commit('live/setGlobalData',liveGlobalData)
  // 如果是直播iframe套壳打开mp项目--end
  store.commit('updateLoadingStatus', {
    isLoading: true
  })

  let u = navigator.userAgent;
  let isAnd = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;//andrio终端
  //假设数据结束
  
  // 如果是发售云-点金计划跳转会强制回到首页，重定向到发售云首页
  if(localStorage.getItem("isFaShou") == 1 && to.path=="/"){
    const p ='/fashou/activity';
    next(p);
  }
  //微信支付成功后跳转页面--针对服务商二级商户 商家小票的跳转（点金计划）
  if (to.query.isFromWechatPay && to.query.isFromWechatPay != undefined && to.query.isFromWechatPay == 1 && localStorage.getItem("goldPlanBackUrl")) {
    let wPBackUrl = localStorage.getItem("goldPlanBackUrl");
    let p = wPBackUrl.split("#")[1];
    
    if (p) {
      next(p);
    } else {
      next();
    }
    return;
  }

  // 履约小程序处理链接直接携带cut进行授权获取数据
  if (((to.path.includes('clearLocalStorage') && to.query.fromckjr2 == "2") || (cId == 'b9ke5w' && to.query.iudgeedu && to.query.iudgeedu == 1) || ((cId == '36wegp' || cId == 'lj7l') && to.query.yp && to.query.yp == 1) || (to.query && to.query.isKpStudy)) && to.query.c == cId && to.query.u && to.query.t) {
    //此处为了我们自己测试用 cId == b9ke5w是有迹的私人订制
    //cId == 36wegp是优匹私人订制
    let c = to.query.c;
    let u = to.query.u;
    let t = to.query.t;
    if (isAnd && utilJs.isWeiXin()) { //测试用
      let exp = new Date();
      if (localStorage.getItem("companyId")) {
        // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
        exp.setTime(exp.getTime() - 1);
        document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
      }
      exp.setTime(exp.getTime() + 30*24*60*60*1000);
      document.cookie = c + "|token=" + t + ";expires=" + exp.toGMTString() + ";path=/";
    }
    window.localStorage.setItem("companyId", c);
    window.localStorage.setItem(c, c);
    window.localStorage.setItem("userId", u);
    window.localStorage.setItem("token", t);
    window.localStorage.setItem(c + "|token", t);
    next();
    return;
  }
  //检验当前页面需不需要微信授权才可进入
  if(utilJs.checkNoNeedAuth(to.path)){
    next();
    return;
  }
  //缓存refereeId
  let reIdArr = window.location.href.split('refereeId=');
  if (reIdArr.length > 1 && reIdArr[1]) {
    let rId = reIdArr[1].split('&').length > 0 ? reIdArr[1].split('&')[0] : reIdArr[1];
    if (!localStorage.getItem(cId) || (localStorage.getItem(cId) && ((localStorage.getItem("userId") && localStorage.getItem("userId") != rId)) || (!localStorage.getItem("userId") && localStorage.getItem("isVisitor")))) {
      window.localStorage.setItem("refereeId", rId); //注册即绑定
      window.localStorage.setItem("reservedRefereeId", rId); //购买即绑定
      window.sessionStorage.setItem("protectRefereeId", rId); // 预绑定
    }
  }
  //缓存股东id-股东模式
  let shIdArr = window.location.href.split('shareholderId=');
  if (shIdArr.length > 1 && shIdArr[1]) {
    let shId = shIdArr[1].split('&').length > 0 ? shIdArr[1].split('&')[0] : shIdArr[1];
    if (shId) {
      window.localStorage.setItem("shareholderId", shId);
    }
  }
  
  //子店铺id
  let paIdArr = window.location.href.split('promotedAccountId=');
  if (paIdArr.length > 1 && paIdArr[1]) {
    let paId = paIdArr[1].split('&').length > 0 ? paIdArr[1].split('&')[0] : paIdArr[1];
    if (paId && paId != '0') {
      sessionStorage.setItem('promotedAccountId', paId);
    }
  }

  // 活动票券必须微信环境下打开，为了支持5000人峰会，防止用户直接点击短信链接跳转到普通浏览器（需要手机号登录），不一定每个用户都绑手机号
  const isLogin = !(localStorage.getItem("isVisitor") && localStorage.getItem("isVisitor") == 1) && localStorage.getItem(localStorage.getItem(cId) + '|token')
  if(!utilJs.isWeiXin() && !isLogin && to.path.includes('activity/ticketNum')){
    let refereeId = window.localStorage.getItem("refereeId") ? window.localStorage.getItem("refereeId") : '';
    let wechatAuthUrl = `/homePage/login/wechatAuthPage?merchantId=${cId}&refereeId=${refereeId}`;
    let tf = to.path != '/homePage/login/wechatAuthPage' && to.path != '/homePage/login/bindMobile' ? to.fullPath : (localStorage.getItem("beforeLoginUrl") || '/');
    localStorage.setItem("beforeLoginUrl", tf);
    next(wechatAuthUrl);
    return
  }

  let isApp = navigator.userAgent.indexOf('IOSLogin') > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf('IOSNewApp') > -1 || navigator.userAgent.indexOf('APPLogin') > -1;
  const ua = window.navigator.userAgent.toLowerCase()
  const wxAppEnvironment = localStorage.getItem("wxAppEnvironment")
  const isWx = utilJs.isWeiXin() && ua.match(/wxwork/i) != "wxwork" && !wxAppEnvironment
  const isQywx = utilJs.isWeiXin() && (ua.match(/wxwork/i) == "wxwork" || wxAppEnvironment == 'wxwork')
  // 企微环境打开小程序
  const isQywxApp = isQywx && utilJs.checkWxApp();

  // 企微环境下 && 非小程序 && 非游客 && 已登录，需要做退登处理（实际就是不让h5在企微登录）
  if (isQywx && !isQywxApp && !(localStorage.getItem("isVisitor") && localStorage.getItem("isVisitor") == 1) && localStorage.getItem(localStorage.getItem(cId) + '|token')) {
    window.localStorage.clear();
    utilJs.setStoreId();
    getVisitor(cId);
    if (unLookPath(to.path)) {
      next('/');
    } else {
      next();
    }
    return;
  }

  // 是否是企微环境下游客模式
  const isQwVisitor = isQywx && localStorage.getItem("isVisitor") && localStorage.getItem("isVisitor") == 1
  // 企微环境下：小程序，走游客+手机号登录；h5，走游客模式+微信登录（实际就是不让h5在企微登录，企微做不了h5微信授权，会提示到微信打开）
  // 企微环境下的游客模式 && (企微打开套壳小程序 || (企微打开H5 && 访问的链接是游客可浏览的页面 && 非手机登录页))
  const isQywxVisitor = isQwVisitor && (isQywxApp || (!isQywxApp && !unLookPath(to.path) && to.path != '/homePage/login/bindMobile'))
  if (!isWx && !isApp && (!localStorage.getItem(localStorage.getItem(cId) + '|token') || isQywxVisitor)) {
    if (!!navigator.userAgent.match(/AppleWebKit.*Mobile.*/) || isQywx) {
      //(非微信浏览器 || 企微浏览器)，并且是app浏览器，不是app端, 比如说抖音浏览器，快手浏览器, 先进入游客模式
      //需要同步请求
      getVisitor(cId);
      if (isQywx) {
        // 企微环境打开h5，需要缓存登陆前页面，后续复制链接到微信打开需要用到
        let tf = to.path != '/homePage/login/wechatAuthPage' && to.path != '/homePage/login/bindMobile' ? to.fullPath : (localStorage.getItem("beforeLoginUrl") || '/');
        localStorage.setItem("beforeLoginUrl", tf);
      }
      if (unLookPath(to.path)) { // 非游客页面会自动跳手机号登陆
        let qrPath = '/homePage/login/bindMobile?isLogin=1&refereeId=' +  window.localStorage.getItem("refereeId");
        next(qrPath);
      } else {
        next();
      }
      return;
    } else {
      //判断非微信&&无token，则跳到qrLogin（pc端） 如果是qrLogin不需要微信验证, 不是app，并且不是手机浏览器的情况下
      if (!to.path.includes('homePage/login/qrLogin')) {
        localStorage.setItem('pcFromPath', to.fullPath);
        let qrPath = '/homePage/login/qrLogin';
        next(qrPath);
        return;
      } else {
        next();
        return;
      }
    }
  }
  if (!utilJs.isWeiXin()) {
    if (!isApp && localStorage.getItem("isVisitor") && localStorage.getItem(localStorage.getItem(cId) + '|token') && unLookPath(to.path)) {
      let qrPath = '/homePage/login/bindMobile?isLogin=1&refereeId=' +  window.localStorage.getItem("refereeId");
      next(qrPath);
      return;
    }
  }

  //缓存埋点数据
  let mdArr = window.location.href.indexOf("sourceForm=") > -1 ? window.location.href.split('sourceForm=') : [];
  if (mdArr.length > 1 && mdArr[1]) {
    let md = mdArr[1].split('&').length > 0 ? mdArr[1].split('&')[0] : mdArr[1];
    window.localStorage.setItem("sourceForm", md);
  }

  let localCompanyId = localStorage.getItem(cId);
  if (cId && localCompanyId) {
    let hasToken = true; //解决微信安卓手机切换账号微信不清除localStorage
    if (isAnd && utilJs.isWeiXin()) {
      let cook = document.cookie;
      let ti = localCompanyId + "|token=";
      if (cook && cook.indexOf(ti) != -1) {
        hasToken = true;
      } else {
        hasToken = false;
      }
    }
    
    if (hasToken && localStorage.getItem(localCompanyId + "|token")) {
      //191115 document.getElementsByTagName('meta')[name="referrer"]["content"] = 'no-referrer';
      if (utilJs.isWeiXin() && localStorage.getItem("isVisitor") == 1 && 
       (to.path != '/' && to.path != '' && to.path != '/homePage/microPage/microPage' && to.path != '/homePage/login/wechatAuthPage' && to.path != '/fashou/activity')) {
        //微信浏览器下游客模式除了这几个页面都跳转到授权页面
        const {prodId,prodType} = getLoginSource(to);
        let refereeId = window.localStorage.getItem("refereeId") ? window.localStorage.getItem("refereeId") : '';
        let wechatAuthUrl = `/homePage/login/wechatAuthPage?merchantId=${cId}&refereeId=${refereeId}&prodId=${prodId}&prodType=${prodType}`;
        let tf = to.path != '/homePage/login/wechatAuthPage' && to.path != '/homePage/login/bindMobile' ? to.fullPath : (localStorage.getItem("beforeLoginUrl") || '/');
        localStorage.setItem("beforeLoginUrl", tf);
        next(wechatAuthUrl);
      } else {
        localStorage.removeItem("beforeLoginUrl");
        next();
      }
    } else {
      let rId = window.localStorage.getItem("refereeId") ? window.localStorage.getItem("refereeId") : '';
      let shId = window.localStorage.getItem("shareholderId") ? window.localStorage.getItem("shareholderId") : '';
      let md = window.localStorage.getItem("sourceForm") ? window.localStorage.getItem("sourceForm") : '';
      initAuthFun(to, next, cId, '', isAnd, rId, shId, md);
    }
  } else {
    let refereeId = window.localStorage.getItem("refereeId") ? window.localStorage.getItem("refereeId") : '';
    let shId = window.localStorage.getItem("shareholderId") ? window.localStorage.getItem("shareholderId") : '';
    let md = window.localStorage.getItem("sourceForm") ? window.localStorage.getItem("sourceForm") : '';
    let url = to.fullPath; //window.location.href;
    let arrObj = url.indexOf('?') != -1 ? url.split("?") : [];
    //存在上次登录地址 || app进入 || 有特定标识fromckjr
    if (arrObj.length > 1 && arrObj[1] && (localStorage.getItem("beforeLoginUrl") || isApp || url.indexOf('&fromckjr=1') != -1)) {
      let arrPara = arrObj[1].split("&");
      let arr;
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split("=");
        if (arr != null) {
          if (localStorage.getItem("companyId")) {
            if (arr[0] === 'c' && localStorage.getItem("companyId") == arr[1] && localStorage.getItem("token") && localStorage.getItem(arr[1] + "|token")) {
              break;
            } else {
              switch (arr[0]) {
                case "c":
                  localStorage.removeItem("companyId");
                  localStorage.removeItem(arr[1]);
                  window.localStorage.setItem("companyId", arr[1]);
                  window.localStorage.setItem(arr[1], arr[1]);
                  break;
                case "u":
                  localStorage.removeItem("userId");
                  window.localStorage.setItem("userId", arr[1]);
                  break;
                case "t":
                  if (arr[1] && arr[1].length > 30) { // 判断大于30位是为了获取路由上的token,因为后台返回的链接可能会带其他含义的t
                    localStorage.removeItem("token");
                    localStorage.removeItem((localStorage.getItem("companyId") || cId) + "|token");
                    window.localStorage.setItem("token", arr[1]);
                    window.localStorage.setItem((localStorage.getItem("companyId") || cId) + "|token", arr[1]);
                    if (isAnd && utilJs.isWeiXin()) {
                      let exp = new Date();
                      exp.setTime(exp.getTime() + 30*24*60*60*1000);
                      document.cookie = (localStorage.getItem("companyId") || cId) + "|token=" + arr[1] + ";expires=" + exp.toGMTString() + ";path=/";
                    }
                  }
                  break;
                case "s":
                  localStorage.removeItem("scopes");
                  window.localStorage.setItem("scopes", arr[1]);
                  break;
                case "refereeId":
                  refereeId = arr[1];
                  window.localStorage.setItem("refereeId", refereeId);
                  break;
              }
            }
          } else {
            switch (arr[0]) {
              case "c":
                localStorage.removeItem("companyId");
                localStorage.removeItem(arr[1]);
                window.localStorage.setItem("companyId", arr[1]);
                window.localStorage.setItem(arr[1], arr[1]);
                break;
              case "u":
                localStorage.removeItem("userId");
                window.localStorage.setItem("userId", arr[1]);
                break;
              case "t":
                if (arr[1] && arr[1].length > 30) { // 判断大于30位是为了获取路由上的token,因为后台返回的链接可能会带其他含义的t
                  localStorage.removeItem("token");
                  localStorage.removeItem((localStorage.getItem("companyId") || cId) + "|token");
                  window.localStorage.setItem("token", arr[1]);
                  window.localStorage.setItem((localStorage.getItem("companyId") || cId) + "|token", arr[1]);
                  if (isAnd && window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger') {
                    let exp = new Date();
                    exp.setTime(exp.getTime() + 30*24*60*60*1000);
                    document.cookie = (localStorage.getItem("companyId") || cId) + "|token=" + arr[1] + ";expires=" + exp.toGMTString() + ";path=/";
                  }
                }
                break;
              case "s":
                localStorage.removeItem("scopes");
                window.localStorage.setItem("scopes", arr[1]);
                break;
              case "refereeId":
                refereeId = arr[1];
                window.localStorage.setItem("refereeId", refereeId);
                break;
            }
          }
        }
      }
      
      if (localStorage.getItem("companyId") && localStorage.getItem("token") && localStorage.getItem(localStorage.getItem(cId) + "|token")) {
        //去掉url后面参数中的cut参数，防止复制链接带了这些值***START***
        if(to.query && to.query.c && to.query.u && to.query.t){
          let newPath = '';
          for(let key in to.query){
            if(key == 'c' || key == 'u' || (key == 't')){
              continue;
            }
            newPath += `${key}=${to.query[key]}&`;
          }
          newPath = newPath ? `?${newPath}` : '';
          let newUrl = `${window.location.href.split("#")[0]}#/${to.path}${newPath}`;
          window.history.replaceState('authEnd','',newUrl)
        }
        //去掉url后面参数中的cut参数，防止复制链接带了这些值***END***
        console.log('授权成功后进入流程----',localStorage.getItem("companyId"),localStorage.getItem("token"),localStorage.getItem(localStorage.getItem(cId) + "|token"))
        localStorage.removeItem("beforeLoginUrl");
        next();
      } else {
        console.log('授权后链接没有cut导致失败，重新授权',localStorage.getItem("userId"))
        let u = localStorage.getItem("userId") || '';
        initAuthFun(to, next, cId, u, isAnd, refereeId, shId, md);
      }
    } else {
      console.log('其他异常授权流程')
      initAuthFun(to, next, cId, '', isAnd, refereeId, shId, md);
    }
  }
})
//微信授权
async function initAuthFun(to, next, cId, u, isAnd, refereeId, shId, md) {
  if (isAnd && utilJs.isWeiXin() && localStorage.getItem("companyId")) {
    // 把之前的cookie设置过期，防止cookie不停地增加导致http request 400错误
    let exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = localStorage.getItem("companyId") + "|token=;expires=" + exp.toGMTString() + ";path=/";
  }
  //清理缓存前先取出缓存中的注册来源。防止第二次调用initauthfun的时候被清掉
  const {prodId,prodType} = getLoginSource(to);
  if(prodId){
    window.sessionStorage.setItem('registeredSourceId',prodId)
    window.sessionStorage.setItem('registeredSourceType',prodType)
  }
  let registeredSourceId = window.sessionStorage.getItem('registeredSourceId') || '';
  let registeredSourceType = window.sessionStorage.getItem('registeredSourceType') || '';
  //双授权个人中心用户信息同步的时候，initAuth需要带上更新用户信息标识
  const forceUpdateUw = localStorage.getItem("forceUpdateUw") || '';
  // let tf = localStorage.getItem("beforeLoginUrl") ? localStorage.getItem("beforeLoginUrl") : to.fullPath;
  let tf = to.path != '/homePage/login/wechatAuthPage' && to.path != '/homePage/login/bindMobile' ? to.fullPath : (localStorage.getItem("beforeLoginUrl") || '/');
  window.localStorage.clear();
  window.localStorage.setItem("refereeId", refereeId);
  window.localStorage.setItem("beforeLoginUrl", tf);
  window.localStorage.setItem("reservedRefereeId", refereeId);
  window.localStorage.setItem("shareholderId", shId);
  window.localStorage.setItem("sourceForm", md);
  utilJs.setStoreId();
  if (!u || (u && u == -100)) { //目前应急处理被封商家g7x8正式商家
    let wechatAuthUrl = `/homePage/login/wechatAuthPage?merchantId=${cId}&refereeId=${refereeId}&prodId=${registeredSourceId}&prodType=${registeredSourceType}`;
    if (to.fullPath.includes("homePage/login/wechatAuthPage")) {
      next();
    } else {
      next(wechatAuthUrl);
    }
  } else {
    let q = `c=${cId}&r=${refereeId}&prodId=${registeredSourceId}&prodType=${registeredSourceType}`;
    let evnRes = await utilJs.getEnv()
    if (u != '') {
      q = `${q}&u=${u}`;
    }
    if (evnRes === 'wxApp') {
      q = `${q}&chl=xcx`;
    }
    if (sessionStorage.getItem('promotedAccountId')) {
      let paId = sessionStorage.getItem('promotedAccountId');
      q = `${q}&promotedAccountId=${paId}`;
    }
    if(forceUpdateUw == 1){
      q = `${q}&forceUpdateUw=1`;
    }
    q = `${q}&backUrl=${encodeURIComponent(window.location.href.split("#/")[0] + '#' + tf)}`;
    
    ckjrRequest({url:checkApiHp(`${global.apiurl}mp/initAuth?${q}`)})
    .then(response => {
      console.log('0wechat auth url: ' + response.data)
      if (response.data) {
        let ua = window.navigator.userAgent.toLowerCase();
        if (utilJs.isWeiXin() && ua.match(/wxwork/i) == "wxwork") {
          // 企业微信下要删除刚进入的页面地址
          localStorage.removeItem("beforeLoginUrl");
        }
        window.location.replace(response.data + '&time=' + Date.parse(new Date()));
      }
    }).catch(function (error) { });
  }
}
//游客获取参数
function getVisitor(cId) {
  let postUrl = `${global.apiurl}common/getAnonUserToken?companyId=${cId}`;
  let ua = window.navigator.userAgent.toLowerCase();
  let uaText = !!ua.includes('aweme') ? '' : (!!ua.includes('kwai') ? 'ks' : 'llq');
   ckjrRequest({url: postUrl, headers:{'X-DMP': uaText}}).then((res)=>{
      const result = res.data.data;
     //处理业务逻辑,游客身份,token固定
      window.localStorage.setItem("isVisitor", 1);
      window.localStorage.setItem("companyId", cId);
      window.localStorage.setItem(cId, cId);
      window.localStorage.setItem("userId", result.u);
      window.localStorage.setItem("token", result.t);
      window.localStorage.setItem(cId + "|token", result.t);
      let isAnd = window.navigator.userAgent.indexOf('Android') > -1 || window.navigator.userAgent.indexOf('Adr') > -1;//andrio终端
      if (isAnd && ua.match(/MicroMessenger/i) == 'micromessenger') {
        let exp = new Date();
        exp.setTime(exp.getTime() + 30*24*60*60*1000);
        document.cookie = localStorage.getItem("companyId") + "|token=" + result.t + ";expires=" + exp.toGMTString() + ";path=/";
      }
   })
}

Vue.use(VueLazyload, {
  error: require('./assets/defult270.png'),
  loading: require('./assets/logo.png'),
  attempt: 1
})

import * as filters from './filters'
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

//阿里图片后缀加上缩略图
Vue.prototype.$addXossFilter = function (value, defaultSrc = '') {
  if (value && value != ' ' && typeof(value) == "string") {
    let isNeedCompression = typeof value === "string" && ((value.indexOf(".aliyuncs.com") > -1 && value.indexOf(".aliyuncs.com/assets/") == -1) || (value.indexOf("kposshzcdn.ckjr001.com") > -1 && value.indexOf("kposshzcdn.ckjr001.com/assets/") == -1)) && value.indexOf(".gif") == -1 && value.indexOf(".GIF") == -1 && value.indexOf("?x-oss-process=") == -1;
    value = value.replace('ck-bkt-knowledge-payment.oss-cn-hangzhou.aliyuncs.com', 'kposshzcdn.ckjr001.com'); // use cdn
	  value = value.replace('ck-bkt-kp2-sz.oss-cn-shenzhen.aliyuncs.com', 'kposssz-qn.ckjr001.com'); // use cdn
    value = value.replace('knowledge-payment.oss-cn-beijing.aliyuncs.com', 'cdn-oss-beijing.myckjr.com'); // use cdn
    const isZhiKu = window.location.host.includes('zhiku001.top');
    if(isZhiKu){
      value = value.replace('kposshzcdn.ckjr001.com', 'kposshzcdn.zhiku001.top');
      value = value.replace('kposssz-qn.ckjr001.com', 'kposssz-qn.zhiku001.top');
    }
    if (isNeedCompression) {
      return value + "?x-oss-process=style/w800";//"?x-oss-process=style/common" //"?x-oss-process=style/w800";
    } else {
      return value;
    }
  } else {
    return defaultSrc;
  }
}

// 获取主题色
Vue.prototype.$getThemeColor = function () {
  let themeColor = localStorage.getItem('mb7ThemeColor') || "#ff8831";
  return themeColor;
}

// 判断是否是小程序套壳
Vue.prototype.$isWxApp = function () {
  return !!(localStorage.getItem('isWxApp') == 1) || false;
}

// 判断是否是小程序套壳ios
Vue.prototype.$isWxAppIos = function () {
  return !!(localStorage.getItem('isWxAppIos') == 1) || false;
}

// 判断是否是门店
Vue.prototype.$isStore = function(){
  return utilJs.getStoreId() ? true : false;
}
//一个公用的跳转函数
Vue.prototype.$routerGo = async function (that, type, data) {
  let evnRes = '';
  if(store.state.live.globalData && store.state.live.globalData.openFromBy == 1){
    // 直播里面套iframe的页面特殊处理（getEnv执行不了)
    evnRes = navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == "micromessenger" ?  'gzh': 'qt';
  } else {
    evnRes = await utilJs.getEnv();
  }
  if (isMplivePage(data.path)) {
    that.$destroy();
    let curl = window.location.href;
    if (data.query && typeof data.query == 'object') {
      for (let key in data.query) {
        data.path += (data.path.indexOf('?') == -1 ? '?' : '&') + `${key}=${data.query[key]}`;
      }
    }
    let u = `${window.location.origin}/kpv2plive/${curl.split("/")[4]}/?#${data.path}`;
    // let liveType = data.path && data.path.split('liveType=')[1] ? data.path.split('liveType=')[1].split('&')[0] : -1
    // 0录播  1、2视频直播  3语音  4PPT    5、6互动直播   7转播,   3语音 4ppt 5旧pc直播 这几个类型不跳小程序，小班课也不跳
    // let isLiveRoom = data.path && data.path.includes('homePage/live/liveRoom'); // 3语音 4ppt都只跳liveRoom，所以竖屏的可以直接跳小程序
    // let isPrivateClass = data.path && data.path.includes('homePage/privateClass/privateLiveRoom')
    // let isLiveVHTryRoom = data.path && data.path.includes('homePage/live/liveVHTryRoom') // 可试看直播间
    // let isGoWxapp = ((isLiveRoom && [0,1,2,6,7].includes(liveType * 1)) || !isLiveRoom) && !isPrivateClass && !isLiveVHTryRoom && localStorage.getItem("wxAppVersion")
    // if (evnRes === 'wxApp' && isGoWxapp) {
    //   utilJs.miniProgramGoTo(type, "/pages/home/liveWxApp/index?liveData=" + encodeURIComponent(data.path + '&token=' + localStorage.getItem("token")))
    // } else 
    if (type == "push") {
      window.location.href = u;
    } else {
      window.location.replace(u);
    }
  } else {
    let goPathData = data
    if (evnRes === 'wxApp') {
      goPathData = utilJs.checkIsNativeInMiniPro(data) || utilJs.checkIsWebInMiniPro(data);
    }
    if (goPathData && goPathData.isForbid) { // 部分页面，ios机型禁止跳转
      return
    } else if (goPathData && goPathData.isNative) { // 判断是否需要跳转小程序原生
      if (sessionStorage.getItem('isKpStudy')) {
        // 履约小程序进入课程详情至少要先传递c、u参数
        goPathData.path = `${goPathData.path}${goPathData.path && goPathData.path.includes('?') ? '&' : '?'}c=${localStorage.getItem('companyId')}&u=${localStorage.getItem('userId')}`;
      }
      utilJs.miniProgramGoTo(goPathData.isSwitchTab ? 'switchTab' : goPathData.isReplace ? 'replace' : type, goPathData.path);
      return;
    } else if (type == "push") {
      that.$router.push(goPathData);
    } else {
      that.$router.replace(goPathData);
    }
  }
}

// 用来处理首页价格不同字号
Vue.prototype.$getPriceStyleHtml = function (value, isShowFreeTxt, prodType, decimalClass = 'c-fs20') { // decimalClass 小数点后的数值的样式
  // 判断是否是小程序套壳ios，写在方法里，每次触发的时候再取一次，写最外层只取一次，有可能会有缓存
  let isWxAppIos = !!(localStorage.getItem('isWxAppIos') == 1) || false;
  if (isShowFreeTxt && value != null && Number(value) == 0) {
    return "免费";
  } else {
    let splitPrice = (value.toString().replace(/-/g, '')).split('.')
    let afterPrice = splitPrice[1] ? `<span class="${decimalClass}">.${splitPrice[1]}</span>` : ''
    let wholePrice = `${splitPrice[0]}${afterPrice}`;
    return isWxAppIos && (!prodType || (prodType && prodType != 12)) ? '' : wholePrice;
  }
},

// 判断是否是小程序套壳
Vue.prototype.$unenableTopNav = function () {
  let companyAuth = localStorage.getItem('companyAuth') ? JSON.parse(localStorage.getItem("companyAuth")) : null;
  return companyAuth && companyAuth.companyTopNav && companyAuth.companyTopNav.style && companyAuth.companyTopNav.style == 5 ? true : false;
}
/**
 * 
 * @param {object | string} toastOptions 
 * @param {string} toastOptions.text 提示文案
 * @param {string} toastOptions.type 提示类型  success, warn, cancel, text
 * @param {number} toastOptions.time 提示显示时间
 * @param {string} toastOptions.icon 提示icon
 * @returns 
 */
Vue.prototype.$showCjToast = function (toastOptions){
  return new Promise((resolve) => {
    //如果是字符串，直接提示纯文本
    if(typeof toastOptions == 'string'){
      return Vue.$vux.toast.show({
        text: toastOptions,
        type: 'text',
        onHide: ()=>{
          resolve()
        }
      });
    }
    //如果传的是对象
    const {type = 'success',text,time = 2000,isShowMask = false,icon = ''} = toastOptions;
    return Vue.$vux.toast.show({
      text: text,
      type: type,
      icon: icon,
      time: time,
      isShowMask:isShowMask,
      onHide: ()=>{
        resolve()
      }
    });
  })
}
router.afterEach(function (to) {
  if (store.state.oem_store.isLoading) {
    setTimeout(function () {
      store.commit('updateLoadingStatus', {
        isLoading: false
      });
    }, 1000);
  }
})
let host = window.location.host;
if (host == "localhost:4444" || host == "kptest.ckjr001.com" || host == "kptest2.ckjr001.com" || host == "kptest3.ckjr001.com") {
  utilJs.syncLoadJs( "https://ckjr-static-assets.oss-cn-shanghai.aliyuncs.com/assets/js/vconsole.min.js").then(() => {
    new VConsole(); // eslint-disable-line
  });
}
new Vue({
  store,
  router,
  render: h => h(App),
  beforeCreate: function () {

  }
}).$mount('#app')

